package util;

public class StringUtil {

	private static boolean isParanWellFormatted(String input) {
		int count = 0;
		boolean countValid = false; 
		for (int i = 0; i < input.length(); i++){
		    if (input.charAt(i)=='(') {
		    	count ++;
		    } else if (input.charAt(i)==')') {
		    	count --;
		    }
		}
		
		if(count==0) {
			countValid = true;
		}
		return countValid;
	}
	
	public static String removeParanData(String input) throws Exception {
		String output = null;
		
		if(isParanWellFormatted(input)) {
			int firstIndexOfOpenParan = input.indexOf('(');
			int firstIndexOfCloseParan = input.indexOf(')');
			
			if(firstIndexOfOpenParan == -1) {
				//done
				output = input;
			} else if(firstIndexOfOpenParan < firstIndexOfCloseParan) { // ( comes before )
				//String temp = input.substring(firstIndexOfOpenParan, firstIndexOfCloseParan);
				//if(temp.contains("(")){
					// TODO
					//special case for "For (this is (a test) and) this will fail";
					//it'll return "For and) this will fail"
				//}
				output = input.substring(0, firstIndexOfOpenParan) + input.subSequence(firstIndexOfCloseParan+1, input.length());
				removeParanData(output);
			}
		}
		
		return removeLeadingAndHangingSpaces(output);
	}
	
	public static String getDataInFirstParan(String input) {
		String output = null;
		int firstIndexOfOpenParan = input.indexOf('(');
		int firstIndexOfCloseParan = input.indexOf(')');
		
		if(firstIndexOfOpenParan < firstIndexOfCloseParan) { // ( comes before )
			// TODO consider "For (this is (a test) and) this will fail"
			output = input.substring(firstIndexOfOpenParan+1, firstIndexOfCloseParan);
		}
		
		return output;
	}
	
	public static String removeLeadingAndHangingSpaces(String input) throws Exception {
		try {
			if(input != null & !input.equals("")) {
				String temp = input;
				while(temp.charAt(0)==' ') {
					temp = temp.substring(1, temp.length());
				}
				
				String output = temp;
				int length = output.length();
				while(output.charAt(length-1) ==' ') {
					output = output.substring(0, length-1);
					length = output.length();
				}
				return output;
			}
			return "";
		} catch (Exception e) {
			System.out.println("e: " + input);
			throw e;
		}
	}

}
